package com.wjc.train.business.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.wjc.train.business.service.ISmsService;
import com.wjc.train.common.req.SendSmsTemplate;
import darabonba.core.client.ClientOverrideConfiguration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.CompletableFuture;

/**
 * @author Guessed
 */
@Slf4j
@Service
public class SmsServiceImpl implements ISmsService {

    @Value("${sms.Id:0}")
    private String accessKeyId;

    @Value("${sms.Key:0}")
    private String accessKeySecret;

    @Value("${sms.endPoint:0}")
    private String endPoint;

    @Value("${sms.signName:0}")
    private String signName;


    @Value("${sms.templateCode:0}")
    private String templateCode;


    @Override
    public void sendCode(String phoneNumber, String code) {

        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId(accessKeyId)
                .accessKeySecret(accessKeySecret)
                .build());

        // Configure the Client
        AsyncClient client = AsyncClient.builder()
                .region("cn-shenzhen") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                        ClientOverrideConfiguration.create()
                                .setEndpointOverride(endPoint)
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();

        // Parameter settings for API request
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .phoneNumbers(phoneNumber)
                .signName(signName)
                .templateCode(templateCode)
                .templateParam(JSON.toJSONString(new SendSmsTemplate(code)))
                .build();

        // Asynchronously get the return value of the API request
        CompletableFuture<SendSmsResponse> response = client.sendSms(sendSmsRequest);
        // Synchronously get the return value of the API request
        try {
            SendSmsResponse resp = response.get();
            log.info("短信响应:{}", JSON.toJSONString(resp));
        } catch (Exception  e) {
            throw new RuntimeException(e);
        }

        client.close();
    }

}
